import ProFormUpload from '@/components/ProFormUpload';
import api from '@/pages/Customer/ListManagement/request';
import { PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormDigit, ProFormSwitch, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form } from 'antd';
import { useState } from 'react';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: CustomerListManagementApi.ListResponse;
  onSuccess?: () => void;
  onCancel?: () => void;
}
const defaultFormData: CustomerListManagementApi.FormData = {
  id: '',
  realname: '',
  mobileno: '',
  nickname: '',
  headimg: [],
  status: 0,
  licensePlateNumber: '',
  vin: '',
  password: '',
  integral: 0,
};
function ShopListManagementForm(props: Props) {
  const { data, isEdit = false } = props;

  const [form] = Form.useForm();
  const [formData, setFormData] = useState<CustomerListManagementApi.FormData>({
    ...defaultFormData,
  });
  const [info, setInfo] = useState<Partial<CustomerListManagementApi.InfoResponse>>({});

  const getInfo = async (params: CustomerListManagementApi.InfoParams) => {
    const info = await api.getInfo(params);
    const { headimg, availablePoints: integral, ...data } = info;
    const formData: CustomerListManagementApi.FormData = {
      ...data,
      integral,
      headimg: [],
    };
    if (headimg) {
      formData.headimg = [
        {
          uid: headimg,
          name: headimg,
          url: headimg,
        },
      ];
    }

    setInfo(info);
    form.setFieldsValue(formData);
    setFormData(formData);
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      if (data && data.id) {
        getInfo({ id: data.id });
      }
    } else {
      setInfo({});
      form.resetFields();
      setFormData({ ...defaultFormData });
      props.onCancel?.();
    }
  };
  const onSubmit = async () => {
    const { realname, mobileno, headimg, status, licensePlateNumber, vin, integral, password } =
      formData;
    const { id = '' } = info;
    const nickname = mobileno;
    if (isEdit) {
      const params: CustomerListManagementApi.UpdateParams = {
        id,
        realname,
        mobileno,
        nickname,
        headimg: headimg[0].url,
        status,
        licensePlateNumber,
        vin,
        password: password || null,
      };
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: CustomerListManagementApi.CreateParams = {
        realname,
        mobileno,
        nickname,
        headimg: headimg[0].url,
        status,
        licensePlateNumber,
        vin,
        integral,
      };
      const data = await api.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}客户`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : !!data ? (
          <PlusOutlined />
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <ProFormText
        required
        name="realname"
        label="客户名称"
        placeholder="请输入客户名称"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.realname,
          onChange: (e) => setFormData({ ...formData, realname: e.target.value }),
        }}
      />
      <ProFormText
        required
        name="mobileno"
        label="手机号"
        placeholder="请输入手机号"
        rules={[{ required: true }, { pattern: /^1\d{10}/, message: '请输入正确的手机号' }]}
        fieldProps={{
          value: formData.mobileno,
          onChange: (e) => setFormData({ ...formData, mobileno: e.target.value }),
        }}
      />
      <ProFormText
        required
        name="licensePlateNumber"
        label="车牌号"
        placeholder="请输入车牌号"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.licensePlateNumber,
          onChange: (e) => setFormData({ ...formData, licensePlateNumber: e.target.value }),
        }}
      />
      <ProFormText
        required
        name="vin"
        label="车架号"
        placeholder="请输入车架号"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.vin,
          onChange: (e) => setFormData({ ...formData, vin: e.target.value }),
        }}
      />
      <ProFormDigit
        required
        name="integral"
        min={0}
        disabled={isEdit}
        label="积分"
        placeholder="请输入积分"
        rules={[{ required: true }]}
        fieldProps={{
          value: formData.integral,
          onChange: (value) => setFormData({ ...formData, integral: value || 0 }),
        }}
      />
      {isEdit && (
        <ProFormText.Password
          name="password"
          label="密码"
          placeholder="请输入密码"
          fieldProps={{
            value: formData.password,
            onChange: (e) => setFormData({ ...formData, password: e.target.value }),
          }}
        />
      )}
      <ProFormSwitch
        required
        name="status"
        label="状态"
        placeholder="请选择状态"
        checkedChildren="启用"
        unCheckedChildren="禁用"
        rules={[{ required: true }]}
        fieldProps={{
          checked: !!formData.status,
          onChange: (value) => {
            setFormData({ ...formData, status: value ? 1 : 0 });
          },
        }}
      />
      <ProFormUpload
        name="headimg"
        label="客户头像"
        placeholder="请上传图片"
        max={1}
        rules={[{ required: true }]}
        file={formData.headimg}
        onChangeFile={(file) => {
          setFormData({ ...formData, headimg: file });
        }}
      />
    </DrawerForm>
  );
}

export default ShopListManagementForm;
